package com.interview.javabase.algorithm.链表;

/**
 * @author zhangshguang
 * @date 2020/10/12
 */
public class K个一组翻转链表 {

    public static void main(String[] args) {

        ListNode head = new ListNode(5);
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(2);
        ListNode node4 = new ListNode(1);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode listNode = reverseKGroup(head, 2);
//        ListNode listNode = reverse(head, node2.next);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }

    private static ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return head;
        }

        ListNode yy = new ListNode(0);

        ListNode curl = head;
        ListNode tempHead = head;

        ListNode tail = yy;

        int length = 0;
        while (curl != null) {
            length++;
            ListNode temp = curl.next;
            if (length % k == 0) {

                ListNode i = tempHead;
                ListNode reverse = reverse(tempHead, curl.next);

                tail.next = reverse;
                tempHead = temp;
                tail = i;
            }

            curl = temp;
        }

        tail.next = tempHead;
        return yy.next;
    }

    private static ListNode reverse(ListNode head, ListNode tail) {

        ListNode curl = head;
        ListNode newListNod = null;

        while (curl != null && curl != tail) {
            ListNode item = curl.next;
            curl.next = newListNod;
            newListNod = curl;
            curl = item;
        }

        return newListNod;
    }

    private static ListNode reverse(ListNode head) {

        ListNode curl = head;
        ListNode newListNod = null;

        while (curl != null) {
            ListNode item = curl.next;
            curl.next = newListNod;
            newListNod = curl;
            curl = item;
        }

        return newListNod;
    }
}
